package uk.ac.tees.aetoolkit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
 * JSONParser - used to parse url string for JSON object.
 * 
 * @author Sohail Rahman, Mark Williamson, Robert Sheffield
 * 
 */
public class JSONParser {

	//initialises variables.
	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	//method to get JSON object from the url passed to it.
	public JSONObject getJSONFromUrl(String url) {
		//try to make HTTP request to url.
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			//gets inputstream from url if connection is made.
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			
		} catch (IOException e) {
			e.printStackTrace();
		}

		try {
			//creates buffered reader to read the input stream.
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			//adds lines from the reader to a string.
			while ((line = reader.readLine()) != null) {
				sb.append(line + "n");
			}
			//close inputstream.
			is.close();
			//sets json string to the string recieved.
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// parse the string to a JSON object.
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON object.
		return jObj;

	}
}